package com.shop.admin.dao.user;

import com.shop.jpa.BaseDao;
import com.shop.domain.pink.UserPinkInfo;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface UserPinkInfoDao extends BaseDao<UserPinkInfo, Long> {

    //未中奖用户 修改 总未拼中次数 单轮拼中次数
    @Modifying(clearAutomatically = true)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
   // @Query(value = "update t_user_pink_info i set i.all_not_pz_num=i.all_not_pz_num+1,i.pt_round_num=i.pt_round_num+1 " +
     //       "where i.pink_id= ?1  and exists (select 1 from t_store_pink p where p.uid=i.uid and p.pink_status=2 and p.pink_id=?1 and p.status=1 and p.is_deleted=0) ",nativeQuery = true)
    @Query(value = "update t_user_pink_info i left join t_store_pink p on i.uid= p.uid  set i.all_not_pz_num= i.all_not_pz_num+ 1, i.pt_round_num= i.pt_round_num+ 1 ,i.last_pink_time = now() " +
                  "  where   i.pink_id =?1 and  p.pink_status= 2  and p.pink_id= ?1  and p.status= 1  and p.is_deleted= 0",nativeQuery = true)
    int updateNotPzUserPinkInfo(Long pink_id);

    //中奖用户 修改总拼中次数 拼团轮数+1
    @Modifying(clearAutomatically = true)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    //@Query(value = "update t_user_pink_info i set i.all_pz_num=i.all_pz_num+1,i.pt_num = (CASE WHEN pt_num+1 >5 THEN 1 ELSE pt_num+1 END)  " +
       //     "where i.pink_id=?1  and exists (select 1 from t_store_pink p where p.uid=i.uid and p.pink_status=1 and p.pink_id=?1 and p.status=1 and p.is_deleted=0) ",nativeQuery = true)
    @Query(value = "update t_user_pink_info i left join t_store_pink p on p.uid = i.uid set  i.all_pz_num=i.all_pz_num+1,i.pt_num = (CASE WHEN i.pt_num+1 >5 THEN 1 ELSE i.pt_num+1 END),i.pt_round_num = 0 ,i.last_pink_time = now() " +
            "where i.pink_id =?1  and p.pink_status=1 and p.pink_id=?1 and p.status=1 and p.is_deleted=0 ",nativeQuery = true)
    int updatePzUserPinkInfo(Long pink_id);

    //查询需要续拼的用户
    @Query(value = "select * from  t_user_pink_info i where i.pink_id=1 and exists(select 1 from `t_auto_pink`  p where p.uid = i.uid  and p.create_time>now()-interval 3 minute )",nativeQuery = true)
    List<UserPinkInfo> queryNeedPtPinkInfo(Long pink_id);

    //修改拼团失败提示
    @Modifying(clearAutomatically = true)
    @Query(value = "update t_user_pink_info set auto_fail_msg= ?2 ,auto_time=now() where id=?1 " ,nativeQuery = true)
    int updateAutoPinkFailInfo(Long pink_info_id,String autoFailMsg);

    @Query("from UserPinkInfo where uid=?1 and pinkId=?2")
    UserPinkInfo findByPinkIdAndUserId(Long userId, Long pinkId);

}
